package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.NoticeDateSelectedAdapter;
import com.keyinong.caizhengting.customdatapicker.CalendarCardNotice;
import com.keyinong.caizhengting.customdatapicker.CalendarCardNotice.OnCellClickListener;
import com.keyinong.caizhengting.customdatapicker.CustomDate;
import com.keyinong.caizhengting.customdatapicker.DateUtil;
import com.keyinong.caizhengting.customdatapicker.NoticeCalendarViewAdapter;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author：郑谦
 * @时间：2017-3-20 下午3:47:52
 * @类名：BookingNoticeActivity.java
 * @功能: 午餐订餐
 */
public class BookingNoticeActivity extends Activity implements
        OnCellClickListener {
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    int year;
    int month;
    HttpTools httptools = null;
    int isOne = 0;
    /**
     * 日历的适配器
     */
    NoticeCalendarViewAdapter<CalendarCardNotice> adapter;
    /**
     * 选择的适配器
     */
    NoticeDateSelectedAdapter selectadapter;
    /**
     * 格式转换类
     */
    DecimalFormat df = new DecimalFormat("00");
    String dataSelected = "";
    /**
     * GridView的子item高度
     */
    int viewheight = 0;

    //	NoticeListBean noticelist = null;
    String orderInfo = "";
    private ImageButton img_title_back;
    private TextView tv_title_name;
    private TextView tv_selectDate;
    /**
     * 日历
     */
    private ViewPager vp_calender;
    /**
     * 选择的日期
     */
    private GridView grid_dataSelected;
    /**
     * 提交
     */
    private Button btn_quxiao;
    private boolean flag = true;
    /**
     * 能够点击的日期
     */
    private ArrayList<String> candatelist = new ArrayList<String>();
    /**
     * 当月
     */
    private int curMonth = DateUtil.getMonth();
    /**
     * 当前的年
     */
    private int curYeay = DateUtil.getYear();
    /**
     * 当月的天数
     */
    int currentMonthDays = DateUtil.getMonthDays(curYeay, curMonth);
    /**
     * 当天
     */
    private int curDay = DateUtil.getCurrentMonthDay();
    /**
     * 日历的下标
     */
    private int mCurrentIndex = 0;
    private CalendarCardNotice[] mShowViews;
    private SildeDirection mDirection = SildeDirection.NO_SILDE;
    private ArrayList<String> selectedlist = new ArrayList<String>();
    private OnClickListener onclick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ib_fanhui:
                    finish();
                    break;

            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//					getWindow().addFlags(
//							WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_bookingnotice);
//		SystemBarTintManager tintManager = new SystemBarTintManager(this);
//		tintManager.setStatusBarTintEnabled(true);
//		tintManager.setStatusBarTintColor(getResources().getColor(
//				R.color.white_1));
        getLunch();
//		initRes();
    }

    private void initRes() {
        img_title_back = (ImageButton) findViewById(R.id.ib_fanhui);
        tv_title_name = (TextView) findViewById(R.id.tv_title_name);
        tv_selectDate = (TextView) findViewById(R.id.tv_selectDate);
        vp_calender = (ViewPager) findViewById(R.id.vp_calender);
        grid_dataSelected = (GridView) findViewById(R.id.grid_dataSelected);
        // tv_dataSelected = (TextView) findViewById(R.id.tv_dataSelected);
        img_title_back.setVisibility(View.VISIBLE);
        grid_dataSelected.setFocusable(false);
        btn_quxiao = (Button) findViewById(R.id.btn_quxiao);
        //取消订餐
        btn_quxiao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Booking();
//					flag=false;


            }
        });
        setRes();
        addOnclick();

    }

    public void refresh() {
        onCreate(null);
    }

    /**
     * 设置可取消就餐日期
     */
    private void setRes() {
        //		noticelist = (NoticeListBean) getIntent().getSerializableExtra(
        //				"noticedetail");
        //				tv_title_name.setText(noticelist.getName());
        //		tv_selectDate.setText(DateUtil.getYear() + "." + curMonth);
        //		tv_noticePrice.setText("单价\t"+noticelist.getPrice_per_day()+"");

        selectadapter = new NoticeDateSelectedAdapter(selectedlist,
                BookingNoticeActivity.this);
        grid_dataSelected.setAdapter(selectadapter);
        // 计算可预订的时间
        //		computeCanSelectDate(noticelist.getAvaliable_days());
//		getLunch();
        //		setViewPager();
    }

    /**
     * 获取午餐取消就餐时间
     */
    private void getLunch() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httptools == null) {
            httptools = new HttpTools(BookingNoticeActivity.this);
        }
        httptools.getLunch(token, new JsonGetlunch());
    }

    private void addOnclick() {
        img_title_back.setOnClickListener(onclick);
        //		tv_selectDate.setOnClickListener(onclick);
        //		tv_noticePay.setOnClickListener(onclick);

    }

    /**
     * 可选的日期
     */
    private void computeCanSelectDate(int avaliableDays) {
        String twoavaliabeleDays = Integer.toBinaryString(avaliableDays);
        //		Log.e("lh", twoavaliabeleDays+"");
        for (int i = 0; i < twoavaliabeleDays.length(); i++) {
            if ((1 & (avaliableDays >> i)) == 1) {
                if (curDay + i > currentMonthDays) {
                    if (curMonth == 12) {
                        curMonth = 0;
                    }
                    //					Log.e("lh", df.format(curMonth + 1)
                    //							+ df.format(curDay - currentMonthDays + i));
                    candatelist.add(df.format(curMonth + 1)   //0307
                            + df.format(curDay - currentMonthDays + i));

                } else {
                    //					Log.e("lh", df.format(curMonth) + df.format(curDay + i));
                    candatelist
                            .add(df.format(curMonth) + df.format(curDay + i));
                }
            }
        }
    }

    /**
     * 加载日历
     */
    private void setViewPager() {
        CalendarCardNotice[] views = new CalendarCardNotice[3];
        for (int i = 0; i < 3; i++) {
            views[i] = new CalendarCardNotice(BookingNoticeActivity.this, this, candatelist, curMonth);
        }
        adapter = new NoticeCalendarViewAdapter<CalendarCardNotice>(views);
        vp_calender.setAdapter(adapter);
        vp_calender.setCurrentItem(0);
//		updateCalendarView(0);
        vp_calender.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                Log.e("info", "position----" + position);
                measureDirection(position);
                updateCalendarView(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    private void Booking() {
        btn_quxiao.setEnabled(false);
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        String date = ""; //
        for (int i = 0; i < selectedlist.size(); i++) {
            if (i == selectedlist.size() - 1) {
                date = date + String.valueOf(selectedlist.get(i));
            } else {
                date = date + String.valueOf(selectedlist.get(i)) + ",";
            }
        }
        Log.i("zq", "date------" + date);
        if (date.equals("")) {
            Toast.makeText(getApplicationContext(), "请选择日期", Toast.LENGTH_SHORT).show();
            btn_quxiao.setEnabled(true);
            return;
        }
        HttpTools httpTools = new HttpTools(BookingNoticeActivity.this);
        httpTools.saveLunch(token, date, new JsonBooking());
    }

    /**
     * 点击选择日期
     */
    @Override
    public void clickDate(CustomDate date) {
        Log.e("lh", "选择的日期" + date.toString());
        String selecteddate = date.toString();
        dateSelected(selecteddate);
    }

    @Override
    public void changeDate(CustomDate date) {

        year = date.getYear();
        month = date.getMonth();
        tv_title_name.setText("" + year + "年" + month + "月");
        if (vp_calender.getCurrentItem() == 0) {
            isOne = 0;
        } else {
            isOne = 1;
        }
//         if(adapter!=null){
//		measureDirection(vp_calender.getCurrentItem());
//		updateCalendarView(vp_calender.getCurrentItem());
//}
    }

    /**
     * 再次点击取消选中
     */
    private void dateSelected(String date) {

        boolean isSame = false;
        for (int i = 0; i < selectedlist.size(); i++) {
            if (selectedlist.get(i).equals(date)) {
                dataSelected.replace(selectedlist.get(i), "");//2017-3-8
                selectedlist.remove(i);
                isSame = true;
                continue;
            }

        }
        if (!isSame) {
            selectedlist.add(date);
            dataSelected += date;
        }

        Log.e("lh", selectedlist.size() + "");
        selectadapter.notifyDataSetChanged();
        if (selectedlist.size() - 1 > 0
				/*&& (selectedlist.size() - 1)
						% grid_dataSelected.getNumColumns() == 0*/) {
            setGridviewHeight();
        }
        //		else if(selectedlist.size()>0&&selectedlist.size()<=4){
        //			ViewGroup.LayoutParams params = grid_dataSelected.getLayoutParams();
        //			params.height = viewheight;
        //			grid_dataSelected.setLayoutParams(params);
        //		}
        int listsize = selectedlist.size();
        //		tv_noticeData.setText("天数\t"+listsize);
        //		tv_noticeTotal.setText("总计:"+listsize*noticelist.getPrice_per_day());
        // Utility.setGridViewHeightBasedOnChildren(grid_dataSelected);
        // tv_dataSelected.setText(str);

    }

    //	private void bookingNotice(String about) {
    //		SharedPreferences sp = getSharedPreferences("spuser",
    //				Context.MODE_PRIVATE);
    //		String token = sp.getString("token", "");
    //		String parkid = sp.getString("park_id", "");
    //		HttpTools toolModel = new HttpTools(BookingNoticeActivity.this);
    //		toolModel.bookingNotice(token, parkid, noticelist.getId(), about,
    //				selectedlist, new MyJsonHttpResponseHander(
    //						BookingNoticeActivity.this) {
    ////					@Override
    ////					public void onSuccess(int statusCode, Header[] headers,
    ////							JSONObject response) {
    ////						super.onSuccess(statusCode, headers, response);
    //////						Log.e("lh", response.toString());
    ////						try {
    ////							int status_code = response.getInt("status_code");
    ////							if (status_code == 200) {
    ////								JSONObject data = response
    ////										.getJSONObject("data");
    ////								String payPara = data.getString("payPara");
    ////								orderInfo = payPara;
    ////								Thread payThread = new Thread(payRunnable);
    ////								payThread.start();
    ////							} else {
    ////								String message = response.getString("message");
    ////								MyToast.mToast(BookingNoticeActivity.this,
    ////										message);
    ////							}
    ////						} catch (JSONException e) {
    ////							// TODO Auto-generated catch block
    ////							e.printStackTrace();
    ////						}
    ////					}
    //
    //					@Override
    //					public void mySuccess(Header[] headers, JSONObject response) {
    //						JSONObject data;
    //						try {
    //							data = response
    //									.getJSONObject("data");
    //							String payPara = data.getString("payPara");
    //							orderInfo = payPara;
    //							Thread payThread = new Thread(payRunnable);
    //							payThread.start();
    //						} catch (JSONException e) {
    //							// TODO Auto-generated catch block
    //							e.printStackTrace();
    //						}
    //					}
    //				});
    //	}

    /**
     * 计算日历高度
     */
    private void setGridviewHeight() {

        //		ListAdapter listAdapter = grid_dataSelected.getAdapter();

        for (int i = 0, len = (selectadapter.getCount() + 1) / 2; i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View viewh = selectadapter.getView(i, null, grid_dataSelected);
            viewh.measure(0, 0); // 计算子项View 的宽高
            viewheight = viewh.getMeasuredHeight();
            continue;
        }
        ViewGroup.LayoutParams params = grid_dataSelected.getLayoutParams();
        if (selectedlist.size() % grid_dataSelected.getNumColumns() == 0) {
            params.height = viewheight
                    * (selectedlist.size() / grid_dataSelected.getNumColumns());
        } else {
            params.height = viewheight
                    * (selectedlist.size() / grid_dataSelected.getNumColumns() + 1);
        }


        grid_dataSelected.setLayoutParams(params);
    }

    /**
     * 计算方向
     *
     * @param arg0
     */
    private void measureDirection(int arg0) {

        if (arg0 >= mCurrentIndex) {
            mDirection = SildeDirection.RIGHT;

        } else if (arg0 < mCurrentIndex) {
            mDirection = SildeDirection.LEFT;
        }
        mCurrentIndex = arg0;
    }

    //	@Override
    //	public void changeDate(CustomDate date) {
    //
    //	}

    // 更新日历视图
    private void updateCalendarView(int arg0) {
        mShowViews = adapter.getAllItems();
        if (mDirection == SildeDirection.RIGHT) {
            mShowViews[arg0 % mShowViews.length].rightSlide();
        } else if (mDirection == SildeDirection.LEFT) {
            mShowViews[arg0 % mShowViews.length].leftSlide();
        }
        mDirection = SildeDirection.NO_SILDE;
    }

    enum SildeDirection {
        RIGHT, LEFT, NO_SILDE;
    }

    //	Runnable payRunnable = new Runnable() {
    //		@Override
    //		public void run() {
    //			PayTask aliapy = new PayTask(BookingNoticeActivity.this);
    //			Map<String, String> result = aliapy.payV2(orderInfo, true);
    //
    //			Message msg = new Message();
    //			msg.what = SDK_PAY_FLAG;
    //			msg.obj = result;
    //			mHandler.sendMessage(msg);
    //		}
    //	};

    public class JsonGetlunch extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(BookingNoticeActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            initRes();
            try {
                Log.i("info", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONArray data = response.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject object = data.getJSONObject(i);
                        String date = object.getString("date");
                        String year = date.substring(0,4);
                        if (Calendar.getInstance(Locale.getDefault())
                                .get(Calendar.YEAR) == Integer.valueOf(year)) {
                            Log.w("TAG", year);
                            String riqi = date.substring(4, 7) + date.substring(8, 10);
                            Log.i("info", "--------" + riqi);
                            candatelist.add(riqi);
                        }
                    }
                    setViewPager();
                } else {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public class JsonBooking extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                Log.i("info", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
//					JSONObject data=response.getJSONObject("data");
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
//					finish();
                    selectedlist = new ArrayList<String>();
                    btn_quxiao.setEnabled(true);
//					grid_dataSelected = new
                    getLunch();
                    Intent intent = new Intent();
                    intent.setClass(BookingNoticeActivity.this, BookingNoticeActivity.class);
                    startActivity(intent);
                    finish();
//					refresh();
                } else {
                    selectedlist = new ArrayList<String>();
                    btn_quxiao.setEnabled(true);
//					grid_dataSelected = new
                    getLunch();
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


}
